/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.PrePurchaseRequest;
import me.zhengjie.modules.system.domain.PrePurchaseRequestDetail;
import me.zhengjie.modules.system.domain.vo.PrePurchaseRequestDetailAuditVo;
import me.zhengjie.modules.system.excel.vo.PurchaseRequestDetailVo;
import me.zhengjie.modules.system.repository.PrePurchaseRequestRepository;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.PrePurchaseRequestDetailRepository;
import me.zhengjie.modules.system.service.PrePurchaseRequestDetailService;
import me.zhengjie.modules.system.service.dto.PrePurchaseRequestDetailDto;
import me.zhengjie.modules.system.service.dto.PrePurchaseRequestDetailQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.PrePurchaseRequestDetailMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;
import org.springframework.web.multipart.MultipartFile;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author 李忠臻
* @date 2024-03-08
**/
@Service
@RequiredArgsConstructor
public class PrePurchaseRequestDetailServiceImpl implements PrePurchaseRequestDetailService {

    private final PrePurchaseRequestDetailRepository prePurchaseRequestDetailRepository;
    private final PrePurchaseRequestDetailMapper prePurchaseRequestDetailMapper;

    private final PrePurchaseRequestRepository prePurchaseRequestRepository;
    @Override
    public PageResult<PrePurchaseRequestDetailDto> queryAll(PrePurchaseRequestDetailQueryCriteria criteria, Pageable pageable){
        Page<PrePurchaseRequestDetail> page = prePurchaseRequestDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(prePurchaseRequestDetailMapper::toDto));
    }

    @Override
    public List<PrePurchaseRequestDetailDto> queryAll(PrePurchaseRequestDetailQueryCriteria criteria){
        return prePurchaseRequestDetailMapper.toDto(prePurchaseRequestDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public PrePurchaseRequestDetailDto findById(Long id) {
        PrePurchaseRequestDetail prePurchaseRequestDetail = prePurchaseRequestDetailRepository.findById(id).orElseGet(PrePurchaseRequestDetail::new);
        ValidationUtil.isNull(prePurchaseRequestDetail.getId(),"PrePurchaseRequestDetail","id",id);
        return prePurchaseRequestDetailMapper.toDto(prePurchaseRequestDetail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PrePurchaseRequestDetail resources) {
        prePurchaseRequestDetailRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PrePurchaseRequestDetail resources) {
        PrePurchaseRequestDetail prePurchaseRequestDetail = prePurchaseRequestDetailRepository.findById(resources.getId()).orElseGet(PrePurchaseRequestDetail::new);
        ValidationUtil.isNull( prePurchaseRequestDetail.getId(),"PrePurchaseRequestDetail","id",resources.getId());
        prePurchaseRequestDetail.copy(resources);
        prePurchaseRequestDetailRepository.save(prePurchaseRequestDetail);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            prePurchaseRequestDetailRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<PrePurchaseRequestDetailDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PrePurchaseRequestDetailDto prePurchaseRequestDetail : all) {
            Map<String,Object> map = new LinkedHashMap<>();
//            map.put("外键", prePurchaseRequestDetail.getPrePurchaseRequestId());
//            map.put("b2b号", prePurchaseRequestDetail.getB2b());
//            map.put("序号", prePurchaseRequestDetail.getIndex());
            map.put("料號", prePurchaseRequestDetail.getModel());
            map.put("品名", "");
            map.put("規格", "");
            map.put("單位", "PC");
            map.put("数量", prePurchaseRequestDetail.getQuantity());
            map.put("期望交貨日", DateUtil.format(prePurchaseRequestDetail.getExpectedDeliveryDate(), "yyyy/MM/dd"));
            map.put("備註", prePurchaseRequestDetail.getRemark());
            map.put("終端客戶", prePurchaseRequestDetail.getCustomer());
            map.put("客户PO", "");

//            map.put("入库数", prePurchaseRequestDetail.getGodownQuantity());
//            map.put("在途数", prePurchaseRequestDetail.getOnPassageQuantity());
//            map.put("创建者", prePurchaseRequestDetail.getCreateBy());
//            map.put("更新者", prePurchaseRequestDetail.getUpdateBy());
//            map.put("创建日期", prePurchaseRequestDetail.getCreateTime());
//            map.put("更新时间", prePurchaseRequestDetail.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List queryByPrePurchaseRequestId(Long prePurchaseRequestId) {
        return prePurchaseRequestDetailRepository.findByPrePurchaseRequestId(prePurchaseRequestId);
    }

    @Transactional
    @Override
    public void pass(PrePurchaseRequestDetailAuditVo prePurchaseRequestDetailAuditVo) {
        List<PrePurchaseRequestDetail> prePurchaseRequestDetailList =
                prePurchaseRequestDetailRepository.findAllById(prePurchaseRequestDetailAuditVo.getIds());

        if ("直发".equals(prePurchaseRequestDetailAuditVo.getPurchaseAttribute())) {
            Map<String, List<PrePurchaseRequestDetail>> supplierGroupMap = prePurchaseRequestDetailList.stream().
                    collect(Collectors.groupingBy(PrePurchaseRequestDetail::getCustomer));
            if (supplierGroupMap.size() > 1) {
                throw new BadRequestException("直发需要选择相同的客户，请重新选择");
            }
        }

        PrePurchaseRequest prePurchaseRequest = new PrePurchaseRequest();
        prePurchaseRequest.setStatus(0);
        prePurchaseRequest.setSupplierName(prePurchaseRequestDetailAuditVo.getSupplierName());
        prePurchaseRequest.setPurchaseAttribute(prePurchaseRequestDetailAuditVo.getPurchaseAttribute());
        prePurchaseRequest.setRows(prePurchaseRequestDetailList.size());
        prePurchaseRequestRepository.save(prePurchaseRequest);

        for(PrePurchaseRequestDetail prePurchaseRequestDetail : prePurchaseRequestDetailList) {
            prePurchaseRequestDetail.setStatus(1);
            prePurchaseRequestDetail.setPrePurchaseRequestId(prePurchaseRequest.getId());
            prePurchaseRequestDetailRepository.save(prePurchaseRequestDetail);
        }
    }

    @Transactional
    @Override
    public void upload( MultipartFile file) {
//校验采购单文件名是否重复
//        List<PrePurchaseRequest> prePurchaseRequestList = prePurchaseRequestRepository.findByFilename(file.getOriginalFilename());
//        if (CollectionUtil.isNotEmpty(prePurchaseRequestList)) {
//            throw new BadRequestException("上传的附件文件名称已经存在，请核实后重新上传");
//        }

        try {
            List<PurchaseRequestDetailVo> l = EasyExcel.read(file.getInputStream(), PurchaseRequestDetailVo.class, null).sheet().doReadSync();
//            Boolean b = l.stream().filter(s -> s.getB2b() == null || "".equals(s.getB2b())).findAny().isPresent();
//            if (b) {
//                throw new BadRequestException("存在b2b号为空的数据，请补充后重新上传");
//            }
//            PurchaseRequestDetailVo firstPurchaseRequestDetailVo = l.get(0);
//            PrePurchaseRequest prePurchaseRequest = new PrePurchaseRequest();
//            prePurchaseRequest.setB2b(firstPurchaseRequestDetailVo.getB2b());
//            prePurchaseRequest.setStatus(0);
//            prePurchaseRequest.setPurchaseAttribute(purchaseAttribute);
//            prePurchaseRequest.setSupplierName(supplierName);
//            prePurchaseRequest.setFilename(file.getOriginalFilename());
//            prePurchaseRequestRepository.save(prePurchaseRequest);

            for (int i = 0; i < l.size(); i++) {
                PurchaseRequestDetailVo purchaseRequestDetailVo = l.get(i);
                PrePurchaseRequestDetail prePurchaseRequestDetail = new PrePurchaseRequestDetail();
                BeanUtils.copyProperties(purchaseRequestDetailVo, prePurchaseRequestDetail);
                prePurchaseRequestDetail.setIndex(i + 1);
                prePurchaseRequestDetail.setStatus(0);
//                prePurchaseRequestDetail.setPrePurchaseRequestId(prePurchaseRequest.getId());
                prePurchaseRequestDetail.setExpectedDeliveryDate(purchaseRequestDetailVo.getExpectedDeliveryDate() != null ?
                        purchaseRequestDetailVo.getExpectedDeliveryDate() : DateUtil.offsetDay(new Date(), 7));
                prePurchaseRequestDetailRepository.save(prePurchaseRequestDetail);
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMessage());
        }
    }

}